3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Logger\LoggerFactory
;
22 use MediaWiki\MediaWikiServices
;
23 use Wikimedia\ScopedCallback
;
26 * Prepare an edit in shared cache so that it can be reused on edit
28 * This endpoint can be called via AJAX as the user focuses on the edit
29 * summary box. By the time of submission, the parse may have already
30 * finished, and can be immediately used on page save. Certain parser
31 * functions like {{REVISIONID}} or {{CURRENTTIME}} may cause the cache
32 * to not be used on edit. Template and files used are check for changes
33 * since the output was generated. The cache TTL is also kept low for sanity.
38 class ApiStashEdit
extends ApiBase
{
39 const ERROR_NONE
= 'stashed';
40 const ERROR_PARSE
= 'error_parse';
41 const ERROR_CACHE
= 'error_cache';
42 const ERROR_UNCACHEABLE
= 'uncacheable';
43 const ERROR_BUSY
= 'busy';
45 const PRESUME_FRESH_TTL_SEC
= 30;
46 const MAX_CACHE_TTL
= 300; // 5 minutes
47 const MAX_SIGNATURE_TTL
= 60;
49 public function execute() {
50 $user = $this->getUser();
51 $params = $this->extractRequestParams();
53 if ( $user->isBot() ) { // sanity
54 $this->dieWithError( 'apierror-botsnotsupported' );
57 $cache = ObjectCache
::getLocalClusterInstance();
58 $page = $this->getTitleOrPageId( $params );
59 $title = $page->getTitle();
61 if ( !ContentHandler
::getForModelID( $params['contentmodel'] )
62 ->isSupportedFormat( $params['contentformat'] )
65 [ 'apierror-badformat-generic', $params['contentformat'], $params['contentmodel'] ],
70 $this->requireOnlyOneParameter( $params, 'stashedtexthash', 'text' );
74 if ( $params['stashedtexthash'] !== null ) {
75 // Load from cache since the client indicates the text is the same as last stash
76 $textHash = $params['stashedtexthash'];
77 if ( !preg_match( '/^[0-9a-f]{40}$/', $textHash ) ) {
78 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
80 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
81 $text = $cache->get( $textKey );
82 if ( !is_string( $text ) ) {
83 $this->dieWithError( 'apierror-stashedit-missingtext', 'missingtext' );
86 // 'text' was passed. Trim and fix newlines so the key SHA1's
87 // match (see WebRequest::getText())
88 $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
89 $textHash = sha1( $text );
92 $textContent = ContentHandler
::makeContent(
93 $text, $title, $params['contentmodel'], $params['contentformat'] );
95 $page = WikiPage
::factory( $title );
96 if ( $page->exists() ) {
97 // Page exists: get the merged content with the proposed change
98 $baseRev = Revision
::newFromPageId( $page->getId(), $params['baserevid'] );
100 $this->dieWithError( [ 'apierror-nosuchrevid', $params['baserevid'] ] );
102 $currentRev = $page->getRevision();
103 if ( !$currentRev ) {
104 $this->dieWithError( [ 'apierror-missingrev-pageid', $page->getId() ], 'missingrev' );
106 // Merge in the new version of the section to get the proposed version
107 $editContent = $page->replaceSectionAtRev(
110 $params['sectiontitle'],
113 if ( !$editContent ) {
114 $this->dieWithError( 'apierror-sectionreplacefailed', 'replacefailed' );
116 if ( $currentRev->getId() == $baseRev->getId() ) {
117 // Base revision was still the latest; nothing to merge
118 $content = $editContent;
120 // Merge the edit into the current version
121 $baseContent = $baseRev->getContent();
122 $currentContent = $currentRev->getContent();
123 if ( !$baseContent ||
!$currentContent ) {
124 $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ], 'missingrev' );
126 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
127 $content = $handler->merge3( $baseContent, $editContent, $currentContent );
130 // New pages: use the user-provided content model
131 $content = $textContent;
134 if ( !$content ) { // merge3() failed
135 $this->getResult()->addValue( null,
136 $this->getModuleName(), [ 'status' => 'editconflict' ] );
140 // The user will abort the AJAX request by pressing "save", so ignore that
141 ignore_user_abort( true );
143 if ( $user->pingLimiter( 'stashedit' ) ) {
144 $status = 'ratelimited';
146 $status = self
::parseAndStash( $page, $content, $user, $params['summary'] );
147 $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
148 $cache->set( $textKey, $text, self
::MAX_CACHE_TTL
);
151 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
152 $stats->increment( "editstash.cache_stores.$status" );
154 $ret = [ 'status' => $status ];
155 // If we were rate-limited, we still return the pre-existing valid hash if one was passed
156 if ( $status !== 'ratelimited' ||
$params['stashedtexthash'] !== null ) {
157 $ret['texthash'] = $textHash;
160 $this->getResult()->addValue( null, $this->getModuleName(), $ret );
164 * @param WikiPage $page
165 * @param Content $content Edit content
167 * @param string $summary Edit summary
168 * @return string ApiStashEdit::ERROR_* constant
171 public static function parseAndStash( WikiPage
$page, Content
$content, User
$user, $summary ) {
172 $cache = ObjectCache
::getLocalClusterInstance();
173 $logger = LoggerFactory
::getInstance( 'StashEdit' );
175 $title = $page->getTitle();
176 $key = self
::getStashKey( $title, self
::getContentHash( $content ), $user );
178 // Use the master DB to allow for fast blocking locks on the "save path" where this
179 // value might actually be used to complete a page edit. If the edit submission request
180 // happens before this edit stash requests finishes, then the submission will block until
181 // the stash request finishes parsing. For the lock acquisition below, there is not much
182 // need to duplicate parsing of the same content/user/summary bundle, so try to avoid
183 // blocking at all here.
184 $dbw = wfGetDB( DB_MASTER
);
185 if ( !$dbw->lock( $key, __METHOD__
, 0 ) ) {
186 // De-duplicate requests on the same key
187 return self
::ERROR_BUSY
;
189 /** @noinspection PhpUnusedLocalVariableInspection */
190 $unlocker = new ScopedCallback( function () use ( $dbw, $key ) {
191 $dbw->unlock( $key, __METHOD__
);
194 $cutoffTime = time() - self
::PRESUME_FRESH_TTL_SEC
;
196 // Reuse any freshly build matching edit stash cache
197 $editInfo = $cache->get( $key );
198 if ( $editInfo && wfTimestamp( TS_UNIX
, $editInfo->timestamp
) >= $cutoffTime ) {
199 $alreadyCached = true;
201 $format = $content->getDefaultFormat();
202 $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
203 $alreadyCached = false;
206 if ( $editInfo && $editInfo->output
) {
207 // Let extensions add ParserOutput metadata or warm other caches
208 Hooks
::run( 'ParserOutputStashForEdit',
209 [ $page, $content, $editInfo->output
, $summary, $user ] );
211 $titleStr = (string)$title;
212 if ( $alreadyCached ) {
213 $logger->debug( "Already cached parser output for key '{cachekey}' ('{title}').",
214 [ 'cachekey' => $key, 'title' => $titleStr ] );
215 return self
::ERROR_NONE
;
218 list( $stashInfo, $ttl, $code ) = self
::buildStashValue(
219 $editInfo->pstContent
,
221 $editInfo->timestamp
,
226 $ok = $cache->set( $key, $stashInfo, $ttl );
228 $logger->debug( "Cached parser output for key '{cachekey}' ('{title}').",
229 [ 'cachekey' => $key, 'title' => $titleStr ] );
230 return self
::ERROR_NONE
;
232 $logger->error( "Failed to cache parser output for key '{cachekey}' ('{title}').",
233 [ 'cachekey' => $key, 'title' => $titleStr ] );
234 return self
::ERROR_CACHE
;
237 // @todo Doesn't seem reachable, see @todo in buildStashValue
238 $logger->info( "Uncacheable parser output for key '{cachekey}' ('{title}') [{code}].",
239 [ 'cachekey' => $key, 'title' => $titleStr, 'code' => $code ] );
240 return self
::ERROR_UNCACHEABLE
;
244 return self
::ERROR_PARSE
;
248 * Check that a prepared edit is in cache and still up-to-date
250 * This method blocks if the prepared edit is already being rendered,
251 * waiting until rendering finishes before doing final validity checks.
253 * The cache is rejected if template or file changes are detected.
254 * Note that foreign template or file transclusions are not checked.
256 * The result is a map (pstContent,output,timestamp) with fields
257 * extracted directly from WikiPage::prepareContentForEdit().
259 * @param Title $title
260 * @param Content $content
261 * @param User $user User to get parser options from
262 * @return stdClass|bool Returns false on cache miss
264 public static function checkCache( Title
$title, Content
$content, User
$user ) {
265 if ( $user->isBot() ) {
266 return false; // bots never stash - don't pollute stats
269 $cache = ObjectCache
::getLocalClusterInstance();
270 $logger = LoggerFactory
::getInstance( 'StashEdit' );
271 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
273 $key = self
::getStashKey( $title, self
::getContentHash( $content ), $user );
274 $editInfo = $cache->get( $key );
275 if ( !is_object( $editInfo ) ) {
276 $start = microtime( true );
277 // We ignore user aborts and keep parsing. Block on any prior parsing
278 // so as to use its results and make use of the time spent parsing.
279 // Skip this logic if there no master connection in case this method
280 // is called on an HTTP GET request for some reason.
281 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
282 $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
283 if ( $dbw && $dbw->lock( $key, __METHOD__
, 30 ) ) {
284 $editInfo = $cache->get( $key );
285 $dbw->unlock( $key, __METHOD__
);
288 $timeMs = 1000 * max( 0, microtime( true ) - $start );
289 $stats->timing( 'editstash.lock_wait_time', $timeMs );
292 if ( !is_object( $editInfo ) ||
!$editInfo->output
) {
293 $stats->increment( 'editstash.cache_misses.no_stash' );
294 $logger->debug( "Empty cache for key '$key' ('$title'); user '{$user->getName()}'." );
298 $age = time() - wfTimestamp( TS_UNIX
, $editInfo->output
->getCacheTime() );
299 if ( $age <= self
::PRESUME_FRESH_TTL_SEC
) {
300 // Assume nothing changed in this time
301 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
302 $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
303 } elseif ( isset( $editInfo->edits
) && $editInfo->edits
=== $user->getEditCount() ) {
304 // Logged-in user made no local upload/template edits in the meantime
305 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
306 $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
307 } elseif ( $user->isAnon()
308 && self
::lastEditTime( $user ) < $editInfo->output
->getCacheTime()
310 // Logged-out user made no local upload/template edits in the meantime
311 $stats->increment( 'editstash.cache_hits.presumed_fresh' );
312 $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
314 // User may have changed included content
319 $stats->increment( 'editstash.cache_misses.proven_stale' );
320 $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
321 } elseif ( $editInfo->output
->getFlag( 'vary-revision' ) ) {
322 // This can be used for the initial parse, e.g. for filters or doEditContent(),
323 // but a second parse will be triggered in doEditUpdates(). This is not optimal.
324 $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
325 } elseif ( $editInfo->output
->getFlag( 'vary-revision-id' ) ) {
326 // Similar to the above if we didn't guess the ID correctly.
327 $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
335 * @return string|null TS_MW timestamp or null
337 private static function lastEditTime( User
$user ) {
338 $db = wfGetDB( DB_REPLICA
);
339 $actorQuery = ActorMigration
::newMigration()->getWhere( $db, 'rc_user', $user, false );
340 $time = $db->selectField(
341 [ 'recentchanges' ] +
$actorQuery['tables'],
343 [ $actorQuery['conds'] ],
349 return wfTimestampOrNull( TS_MW
, $time );
353 * Get hash of the content, factoring in model/format
355 * @param Content $content
358 private static function getContentHash( Content
$content ) {
359 return sha1( implode( "\n", [
360 $content->getModel(),
361 $content->getDefaultFormat(),
362 $content->serialize( $content->getDefaultFormat() )
367 * Get the temporary prepared edit stash key for a user
369 * This key can be used for caching prepared edits provided:
370 * - a) The $user was used for PST options
371 * - b) The parser output was made from the PST using cannonical matching options
373 * @param Title $title
374 * @param string $contentHash Result of getContentHash()
375 * @param User $user User to get parser options from
378 private static function getStashKey( Title
$title, $contentHash, User
$user ) {
379 return ObjectCache
::getLocalClusterInstance()->makeKey(
381 md5( $title->getPrefixedDBkey() ),
382 // Account for the edit model/text
384 // Account for user name related variables like signatures
385 md5( $user->getId() . "\n" . $user->getName() )
390 * Build a value to store in memcached based on the PST content and parser output
392 * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
394 * @param Content $pstContent Pre-Save transformed content
395 * @param ParserOutput $parserOutput
396 * @param string $timestamp TS_MW
398 * @return array (stash info array, TTL in seconds, info code) or (null, 0, info code)
400 private static function buildStashValue(
401 Content
$pstContent, ParserOutput
$parserOutput, $timestamp, User
$user
403 // If an item is renewed, mind the cache TTL determined by config and parser functions.
404 // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
405 $since = time() - wfTimestamp( TS_UNIX
, $parserOutput->getCacheTime() );
406 $ttl = min( $parserOutput->getCacheExpiry() - $since, self
::MAX_CACHE_TTL
);
408 // Avoid extremely stale user signature timestamps (T84843)
409 if ( $parserOutput->getFlag( 'user-signature' ) ) {
410 $ttl = min( $ttl, self
::MAX_SIGNATURE_TTL
);
414 // @todo It doesn't seem like this can occur, because it would mean an entry older than
415 // getCacheExpiry() seconds, which is much longer than PRESUME_FRESH_TTL_SEC, and
416 // anything older than PRESUME_FRESH_TTL_SEC will have been thrown out already.
417 return [ null, 0, 'no_ttl' ];
420 // Only store what is actually needed
421 $stashInfo = (object)[
422 'pstContent' => $pstContent,
423 'output' => $parserOutput,
424 'timestamp' => $timestamp,
425 'edits' => $user->getEditCount()
428 return [ $stashInfo, $ttl, 'ok' ];
431 public function getAllowedParams() {
434 ApiBase
::PARAM_TYPE
=> 'string',
435 ApiBase
::PARAM_REQUIRED
=> true
438 ApiBase
::PARAM_TYPE
=> 'string',
441 ApiBase
::PARAM_TYPE
=> 'string'
444 ApiBase
::PARAM_TYPE
=> 'text',
445 ApiBase
::PARAM_DFLT
=> null
447 'stashedtexthash' => [
448 ApiBase
::PARAM_TYPE
=> 'string',
449 ApiBase
::PARAM_DFLT
=> null
452 ApiBase
::PARAM_TYPE
=> 'string',
455 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
456 ApiBase
::PARAM_REQUIRED
=> true
459 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
460 ApiBase
::PARAM_REQUIRED
=> true
463 ApiBase
::PARAM_TYPE
=> 'integer',
464 ApiBase
::PARAM_REQUIRED
=> true
469 public function needsToken() {
473 public function mustBePosted() {
477 public function isWriteMode() {
481 public function isInternal() {